package com.hwadee.springboot_lx.controller;

import com.hwadee.springboot_lx.service.DataService;
import com.hwadee.springboot_lx.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/backup")
public class BackupController {

    private final RedisService redisService;
    private final DataService dataService;

    @Autowired
    public BackupController(DataService dataService, RedisService redisService) {
        this.redisService = redisService;
        this.dataService = dataService;
    }

    @PostMapping("/backupData")
    public ResponseEntity<String> backupData(@RequestParam String type, @RequestParam String filePath) {
        try {
            if ("database".equalsIgnoreCase(type)) {
                dataService.backupDatabase(filePath);
            } else if ("redis".equalsIgnoreCase(type)) {
                redisService.backupRedis(filePath);
            } else if ("both".equalsIgnoreCase(type)) {
                dataService.backupDatabase(filePath);
                redisService.backupRedis(filePath);
            } else {
                return ResponseEntity.badRequest().body("Invalid backup type");
            }
            return ResponseEntity.ok("Backup successful");
        } catch (IOException e) {
            // 这里打印异常可以选择记录日志，而不是直接打印堆栈
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Backup failed: " + e.getMessage());
        }
    }
}

